using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Generic;

/// <summary>
/// Summary description for AuditLog
/// </summary>
public class AuditLog
{
    HDDatabase HDD = new HDDatabase();
	public AuditLog()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    private bool IsAuditLogged(string Object_id, string Operation, ref List<string> KeyAtt, ref DataRow drAL)
    {
        bool bReturn = false;
        try
        {
            string sSql = "Select * from sy_audit_settings where object_id='" + Object_id + "'";
            
            drAL = HDD.GetTableRow(sSql);
            if (drAL == null) return false;
            string sTemp = drAL[Operation].ToString();
            if (sTemp != "")
                bReturn = Convert.ToBoolean(sTemp);

            sSql = "select af_row_id from sy_obj where object_id='" + Object_id + "'";
            sTemp = HDD.GetColumnValue(sSql);
            sSql = "select * from sy_obj_att where object_id='" + sTemp + "' and [is_primary]='true'";
            DataTable dtKey = HDD.GetDataTable(sSql);
            if (dtKey != null)
            {
                KeyAtt.Add("af_row_id");
                foreach (DataRow dr in dtKey.Rows)
                    KeyAtt.Add(dr["attrib_id"].ToString());
            }
            dtKey.Dispose();
            dtKey = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("IsAuditLogged : Error : " + ex.Message);
            bReturn = false;
        }
        return bReturn;
    }

    private string getLogSeq()
    {
        string sLogSeq = "1";

        try
        {
            string sTemp = HDD.GetColumnValue("Select max(log_seq) from sy_audit_actions");
            if (sTemp != "")
                sLogSeq = Convert.ToString(Convert.ToInt32(sTemp) + 1);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getLogSeq : Error : " + ex.Message);
            return "1";
        }
        return sLogSeq;
    }

    private void InsertAuditLogRecords(List<string> SQL)
    {
        SqlConnection sqlConn = null;
        SqlCommand sqlComm = null;
        try
        {
            sqlConn = new SqlConnection(HttpContext.Current.Session["dbcon"].ToString());
            sqlConn.Open();
            foreach (string sTemp in SQL)
            {
                sqlComm = new SqlCommand(sTemp, sqlConn);
                sqlComm.ExecuteNonQuery();
            }
            sqlComm.Dispose();
            sqlComm = null;
            sqlConn.Close();
            sqlConn.Dispose();
            sqlConn = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("InsertAuditLogRecords : Error : " + ex.Message);
            sqlComm.Dispose();
            sqlComm = null;
            sqlConn.Close();
            //sqlConn.Dispose();
            sqlConn = null;
        }
    }

    private string GetOldValue(DataRow PageInfo, string KeyValue, string ColumnName)
    {
        string sReturn = null;
        try
        {
            DataTable dt = GlobalValues.dsAudit.Tables[PageInfo["page_id"].ToString()];
            if (dt != null)
            {
                DataRow[] drr = dt.Select("af_row_id='" + KeyValue + "'");
                if (drr.Length > 0)
                    sReturn = drr[0][ColumnName].ToString();
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("GetOldValue : Error : " + ex.Message);
            sReturn = null;
        }
        return sReturn;
    }

    private void logAllValues(DataRow drPageInfo, DataRow InputInfo, ref List<string> SQL, ref DataTable dt, ref DataSet dsPageInfo, string Operation, string AF_ROW_ID, ref ScreenReader SR, ref List<string> KeyAtt)
    {
        string sTemp = "";
        int iAttribSeq = 1;
        foreach (DataColumn dc in dt.Columns)
        {
            try
            {
                if (!KeyAtt.Contains(dc.ColumnName))
                {
                    switch (Operation)
                    {
                        case "INSERT":
                        case "DELETE":
                            // Added by srivatsan on June 15 2009 for owner id field
                            sTemp = "INSERT INTO [sy_audit_log_value]([attrib_seq],[attrib_id],[new_value],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by],[log_seq]) VALUES (" + iAttribSeq + ",'" + dc.ColumnName + "','" + InputInfo[dc.ColumnName].ToString() + "','" + SR.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + AF_ROW_ID + "')";
                            break;
                        case "UPDATE":
                            // Added by srivatsan on June 15 2009 for owner id field
                            string sOldValue = GetOldValue(drPageInfo, InputInfo["af_row_id"].ToString(), dc.ColumnName);
                            sTemp = "INSERT INTO [sy_audit_log_value]([attrib_seq],[attrib_id],[old_value],[new_value],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by],[log_seq]) VALUES (" + iAttribSeq + ",'" + dc.ColumnName + "','" + sOldValue + "','" + InputInfo[dc.ColumnName].ToString() + "','" + SR.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + AF_ROW_ID + "')";
                            break;
                    }
                    iAttribSeq++;
                    SQL.Add(sTemp);
                }
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog("logAllValues : Error : " + ex.Message);
            }
        }
    }

    private void logKeyValues(DataRow drPageInfo, DataRow InputInfo, ref List<string> SQL, ref DataTable dt, ref DataSet dsPageInfo, string Operation, string AF_ROW_ID, ref ScreenReader SR, ref List<string> KeyAtt)
    {
        string sTemp = "";
        int iAttribSeq = 1;
        //foreach (DataColumn dc in dt.Columns)
        //{
            try
            {
                if (KeyAtt.Count == 0)// Added by srivatsan on June 15 2009 for owner id field
                    sTemp = "INSERT INTO [sy_audit_log_key]([key_seq],[attrib_id],[key_value],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by],[log_seq]) VALUES (1,'af_row_id','" + InputInfo["af_row_id"].ToString() + "','" + SR.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + AF_ROW_ID + "')";
                else
                {
                    foreach (string ColName in KeyAtt)
                    {
                        switch (Operation)
                        {
                            case "INSERT":
                            case "DELETE":// Added by srivatsan on June 15 2009 for owner id field
                                sTemp = "INSERT INTO [sy_audit_log_key]([key_seq],[attrib_id],[key_value],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by],[log_seq]) VALUES (" + iAttribSeq + ",'" + ColName + "','" + InputInfo[ColName].ToString() + "','" + SR.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + AF_ROW_ID + "')";
                                break;
                            case "UPDATE":// Added by srivatsan on June 15 2009 for owner id field
                                string sOldValue = GetOldValue(drPageInfo, InputInfo["af_row_id"].ToString(), ColName);
                                sTemp = "INSERT INTO [sy_audit_log_key]([key_seq],[attrib_id],[old_value],[key_value],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by],[log_seq]) VALUES (" + iAttribSeq + ",'" + ColName + "','" + sOldValue + "','" + InputInfo[ColName].ToString() + "','" + SR.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + AF_ROW_ID + "')";
                                break;
                        }
                        SQL.Add(sTemp);
                        iAttribSeq++;
                    }
                }
                
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog("logKeyValues : Error : " + ex.Message);
            }
        //}
    }

    private void InsertAuditLog(DataRow PageInfo, ref DataSet InputInfo, bool Result, string Operation, ref List<string> KeyAtt, ref DataRow drAL)
    {
        try
        {
            List<string> sSql = new List<string>();
            string sTemp = "";
            DataTable dt = InputInfo.Tables[PageInfo["page_id"].ToString()];
            string sLogSeq = getLogSeq();
            ScreenReader SR = new ScreenReader();
            string sAF_ROW_ID = SR.getHashKey();

            //bool bLogAll = false; // Commented by 'Imran Gani' on 31-Oct-2013, to log changed values
            //bLogAll = Convert.ToBoolean(drAL["log_all_values"].ToString() == "" ? "false" : drAL["log_all_values"].ToString());

            string sLogType = string.Empty; // Added by 'Imran Gani' on 31-Oct-2013, to log changed values
            sLogType = drAL["log_all_values"].ToString();

            /*if (Operation != "DELETE")
            {
                sTemp = HDD.GetColumnValue("select log_key_values_only from sy_audit_settings where object_id='" + PageInfo["object_id"].ToString() + "'");
                if (sTemp != "")
                    bOnlyKey = Convert.ToBoolean(sTemp);
            } */

            // Added by srivatsan on June 15 2009 for owner id field
            sTemp = "insert into sy_audit_actions ([log_seq],[object_id],[action_by],[action],[action_result],[log_date],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by]) values (" + sLogSeq + ",'" + PageInfo["object_id"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + Operation + "','" + Result + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + sAF_ROW_ID + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "')";
            sSql.Add(sTemp);
            foreach (DataRow dr in dt.Rows)
            {
                logKeyValues(PageInfo, dr, ref sSql, ref dt, ref InputInfo, Operation, sAF_ROW_ID, ref SR, ref KeyAtt);
                //if (bLogAll)
                if (sLogType.ToUpper() == "LAV")
                {
                    logAllValues(PageInfo, dr, ref sSql, ref dt, ref InputInfo, Operation, sAF_ROW_ID, ref SR, ref KeyAtt);
                }
                else if (sLogType.ToUpper() == "LCV")
                {
                    logChangedValues(PageInfo, dr, ref sSql, ref dt, ref InputInfo, Operation, sAF_ROW_ID, ref SR, ref KeyAtt);
                }
                //else
                //{
                    
                //    /*sTemp = "INSERT INTO [sy_audit_log_key]([key_seq],[attrib_id],[key_value],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[log_seq]) VALUES (1,'af_row_id','" + dr["af_row_id"].ToString() + "','" + SR.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + sAF_ROW_ID + "')";
                //    sSql.Add(sTemp);*/
                //}
            }
            SR = null;
            dt = null;
            InsertAuditLogRecords(sSql);
            sSql.Clear();
            sSql = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("InsertAuditLog : Error : " + ex.Message);
        }
    }

    public bool WriteAuditLog(ref DataSet PageInfo, ref DataSet InputInfo, string Operation, bool Result)
    {
        bool bReturn = true;
        try
        {
            if (HttpContext.Current.Request.UrlReferrer!= null)
                if (HttpContext.Current.Request.UrlReferrer.AbsolutePath.ToLower().EndsWith("/reportwizard.aspx"))
                    if (GlobalValues.dsAudit.Tables.Count == 3)
                        if (GlobalValues.dsAudit.Tables[0].TableName == "p_sy_report")
                            Operation = "UPDATE";

            foreach (DataRow dr in PageInfo.Tables["Page"].Rows)
            {
                DataRow drAL = null;
                List<string> sKeyAtt = new List<string>();
                if (IsAuditLogged(dr["object_id"].ToString(), Operation, ref sKeyAtt, ref drAL))
                {
                    if (Operation == "DELETE")
                        InputInfo = GlobalValues.dsAudit;
                    InsertAuditLog(dr, ref InputInfo, Result, Operation, ref sKeyAtt, ref drAL);
                }
            }
            if (GlobalValues.dsAudit.Tables.Count > 0)
                GlobalValues.dsAudit.Tables.Clear();
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("WriteAuditLog : Error : " + ex.Message);
            bReturn = false;
        }
        return bReturn;
    }

    public bool logUserInCompany()
    {
        bool bReturn = true;
        ScreenReader SR = new ScreenReader();
        SqlConnection sqlConn = null;
        SqlCommand sqlCommand = null;
        try
        {
            string[] str = System.Net.Dns.Resolve(HttpContext.Current.Request.ServerVariables["remote_addr"]).HostName.Split('.');
            string sSessionId = SR.getHashKey();
            if (HttpContext.Current.Request.Cookies["ASP.Net_Sessionid"] != null)
                sSessionId = HttpContext.Current.Request.Cookies["ASP.Net_Sessionid"].Value;

            string sTemp = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            if (sTemp.Contains("\\"))
                sTemp = " (" + sTemp.Substring(0, sTemp.IndexOf("\\")) + ")";

            string strUserAgent = HttpContext.Current.Request.UserAgent; // Added by 'Imran Gani' on 27-Jun-2014, for user agent string.
            if (strUserAgent.Length > 1500)
                strUserAgent = strUserAgent.Substring(0, 1500);

            //LogWriter.WriteLog("System.Security.Principal.WindowsIdentity.GetCurrent().Name : " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
            string sSql = "INSERT INTO [sy_userlog] ([session_id],[user],[log_in],[client_addr],[os],[application],[af_row_id],[created_at],[modified_at],[user_agent])" +
                 " VALUES ('" + sSessionId + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString() + sTemp
                 + "','" + HttpContext.Current.Request.Browser.Platform + "','" + HttpContext.Current.Request.Browser.Type
                 + "','" + SR.getHashKey() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + strUserAgent + "') ";
            //HttpContext.Current.Request.Cookies["ASP.Net_Sessionid"].Value
            sqlConn = new SqlConnection(HttpContext.Current.Session["dbcon"].ToString());
            sqlCommand = new SqlCommand(sSql, sqlConn);
            sqlConn.Open();
            sqlCommand.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("logUserInCompany : Error : " + ex.Message);
            bReturn = false;
        }
        finally
        {
            SR = null;
            sqlCommand.Dispose();
            sqlCommand = null;
            sqlConn.Close();
            sqlConn.Dispose();
            sqlConn = null;
        }
        return bReturn;
    }

    public bool logUserInModel(string Company_Id, string User_Name, bool Login_status) // Modified by 'Imran Gani' on 25-Nov-2013, for login status
    {
        bool bReturn = true;
        ScreenReader SR = new ScreenReader();
        SqlCommand sqlCommand = null;
        SqlConnection sqlConn = null;
        try
        {
            string strUserAgent = HttpContext.Current.Request.UserAgent; // Added by 'Imran Gani' on 27-Jun-2014, for user agent string.
            if (strUserAgent.Length > 1500)
                strUserAgent = strUserAgent.Substring(0, 1500);

            string sSessionId = SR.getHashKey(); // Added by 'Imran Gani' on 15-Sep-2014, to include seession id field in Model DB
            if (HttpContext.Current.Request.Cookies["ASP.Net_Sessionid"] != null)
                sSessionId = HttpContext.Current.Request.Cookies["ASP.Net_Sessionid"].Value;

            string sSql = "INSERT INTO [sy_userlog] ([company_id],[user],[log_in],[client_addr],[os],[application],[Login_Status],[af_row_id],[created_at],[modified_at],[user_agent],[session_id])" +
                 " VALUES ('" + Company_Id.Replace("'", "''") + "','" + User_Name + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString()
                 + "','" + HttpContext.Current.Request.Browser.Platform + "','" + HttpContext.Current.Request.Browser.Type + "'," + (Login_status ? 1 : 0)
                 + ",'" + SR.getHashKey() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + strUserAgent + "', '" + sSessionId + "') ";
            //HttpContext.Current.Request.Cookies["ASP.Net_Sessionid"].Value
            sqlConn = new SqlConnection(HttpContext.Current.Session["servercon"].ToString()); // Modified by 'Imran Gani' on 25-Nov-2013, (dbcon -> servercon) to get Model DB connection string
            sqlCommand = new SqlCommand(sSql, sqlConn);
            sqlConn.Open();
            sqlCommand.ExecuteNonQuery();
            
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("logUserInModel : Error : " + ex.Message);
            bReturn = false;
        }
        finally
        {
            sqlCommand.Dispose();
            sqlCommand = null;
            sqlConn.Close();
            sqlConn.Dispose();
            sqlConn = null;
            SR = null;
        }
        return bReturn;
    }

    public bool updateUserInCompany()
    {
        bool bReturn = true;
        SqlConnection sqlConn = null;
        SqlCommand sqlCommand = null;
        try
        {
            string sSql = "update [sy_userlog] set [log_out]='" + DateTime.Now.ToUniversalTime().ToString() + "', [modified_at] = '" + DateTime.Now.ToUniversalTime().ToString() + "' where session_id = '" + HttpContext.Current.Request.Cookies["ASP.Net_Sessionid"].Value + "'";
            sqlConn = new SqlConnection(HttpContext.Current.Session["dbcon"].ToString());
            sqlCommand = new SqlCommand(sSql, sqlConn);
            sqlConn.Open();
            sqlCommand.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("updateUserInCompany : Error : " + ex.Message);
            bReturn = false;
        }
        finally
        {
            if (sqlConn != null)
            {
                if (sqlConn.State.Equals(ConnectionState.Open))
                    sqlConn.Close();
                sqlConn.Dispose();
            }
            if (sqlCommand != null)
                sqlCommand.Dispose();
        }
        return bReturn;
    }

    public bool updateUserInModel() // Added by 'Imran Gani' on 15-Sep-2014, to log logout time in Model DB
    {
        bool bReturn = true;
        SqlConnection sqlConn = null;
        SqlCommand sqlCommand = null;
        try
        {
            string sSql = "update [sy_userlog] set [log_out]='" + DateTime.Now.ToUniversalTime().ToString() + "', [modified_at] = '" + DateTime.Now.ToUniversalTime().ToString() + "' where session_id = '" + HttpContext.Current.Request.Cookies["ASP.Net_Sessionid"].Value + "'";
            sqlConn = new SqlConnection(HttpContext.Current.Session["servercon"].ToString());
            sqlCommand = new SqlCommand(sSql, sqlConn);
            sqlConn.Open();
            sqlCommand.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("updateUserInModel : Error : " + ex.Message);
            bReturn = false;
        }
        finally
        {
            if (sqlConn != null)
            {
                if (sqlConn.State.Equals(ConnectionState.Open))
                    sqlConn.Close();
                sqlConn.Dispose();
            }
            if (sqlCommand != null)
                sqlCommand.Dispose();
        }
        return bReturn;
    }
    
    // Added by 'Imran Gani' on 31-Oct-2013, to log changed values
    private void logChangedValues(DataRow drPageInfo, DataRow InputInfo, ref List<string> SQL, ref DataTable dt, ref DataSet dsPageInfo, string Operation, string AF_ROW_ID, ref ScreenReader SR, ref List<string> KeyAtt)
    {
        string sTemp = "";
        int iAttribSeq = 1;
        foreach (DataColumn dc in dt.Columns)
        {
            try
            {
                if (!KeyAtt.Contains(dc.ColumnName))
                {
                    switch (Operation)
                    {
                        case "INSERT":
                        //case "DELETE":
                            sTemp = "INSERT INTO [sy_audit_log_value]([attrib_seq],[attrib_id],[new_value],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by],[log_seq]) VALUES (" + iAttribSeq + ",'" + dc.ColumnName + "','" + InputInfo[dc.ColumnName].ToString() + "','" + SR.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + AF_ROW_ID + "')";
                            break;
                        case "UPDATE":
                            string sOldValue = GetOldValue(drPageInfo, InputInfo["af_row_id"].ToString(), dc.ColumnName);
                            if (IsNewValue(sOldValue, InputInfo[dc.ColumnName].ToString(), drPageInfo, dc.ColumnName))
                                sTemp = "INSERT INTO [sy_audit_log_value]([attrib_seq],[attrib_id],[old_value],[new_value],[af_row_id],[created_by],[owner_id],[created_at],[modified_at],[modified_by],[log_seq]) VALUES (" + iAttribSeq + ",'" + dc.ColumnName + "','" + sOldValue + "','" + InputInfo[dc.ColumnName].ToString() + "','" + SR.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + AF_ROW_ID + "')";
                            else
                                sTemp = string.Empty;
                            break;
                    }
                    if (!string.IsNullOrEmpty(sTemp))
                    {
                        iAttribSeq++;
                        SQL.Add(sTemp);
                    }
                }
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog("logChangedValues : Error : " + ex.Message);
            }
        }
    }

    /// <summary>
    /// To Write Password Security Log, when user change / reset the Password.
    /// </summary>
    /// <param name="sAction_done_by">Current User ID</param>
    /// <param name="sApplies_to">Target User ID</param>
    /// <param name="sPassword">Encrypted New Password.</param>
    /// <param name="sAction">Change / Reset Password.</param>
    // Added by 'Imran Gani' on 25-Nov-2013.
    public void WritePasswordSecurityLog(string sAction_done_by, string sApplies_to, string sPassword, string sAction)
    {
        ScreenReader SR = new ScreenReader();
        SqlCommand sqlCommand = null;
        SqlConnection sqlConn = null;
        try
        {
            string sSql = "INSERT INTO [sy_password_security_log] ([action_done_by],[applies_to],[password],[action],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id])" +
                 " VALUES ('" + sAction_done_by + "','" + sApplies_to + "','" + sPassword + "','" + sAction + "','" + SR.getHashKey() +
                 "','" + sAction_done_by + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + sAction_done_by + "', 'e51e0327224a2eb9');";
            sqlConn = new SqlConnection(HttpContext.Current.Session["dbcon"].ToString());
            sqlCommand = new SqlCommand(sSql, sqlConn);
            sqlConn.Open();
            sqlCommand.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("AuditLog: WritePasswordSecurityLog : Error : " + ex.Message);
        }
        finally
        {
            if (sqlCommand != null)
                sqlCommand.Dispose();
            if (sqlConn != null)
            {
                if (sqlConn.State.Equals(ConnectionState.Open))
                    sqlConn.Close();
                sqlConn.Dispose();
            }
            SR = null;
        }
    }

    /// <summary>
    /// To compare existing value with new value based on DB datatype.
    /// </summary>
    /// <param name="sOldValue">Existing DB value.</param>
    /// <param name="sCurrentValue">New input value.</param>
    /// <param name="PageInfo">DataRow of PageInfo.</param>
    /// <param name="ColumnName">Column Name of input.</param>
    /// <returns>True - for new value, False - for values are same.</returns>
    // Added by 'Imran Gani' on 10-Mar-2014, for comparing existing value with new value.
    private bool IsNewValue(string sOldValue, string sCurrentValue, DataRow PageInfo, string ColumnName)
    {
        bool sRet = false;
        try
        {
            if (sOldValue != "" || sCurrentValue != "")
            {
                DataTable dt = GlobalValues.dsAudit.Tables[PageInfo["page_id"].ToString()];
                if (dt != null)
                {
                    switch (dt.Columns[ColumnName].DataType.ToString().ToLower())
                    {
                        case "system.double":
                        case "system.decimal":
                        case "system.int32":
                            if (sOldValue != "" && sCurrentValue != "")
                            {
                                if (double.Parse(sOldValue) != double.Parse(sCurrentValue))
                                    sRet = true;
                            }
                            else if (sOldValue != sCurrentValue)
                                sRet = true;
                            break;
                        case "system.datetime":
                            if (sOldValue != "" && sCurrentValue != "")
                            {
                                if (DateTime.Parse(sOldValue) != DateTime.Parse(sCurrentValue))
                                    sRet = true;
                            }
                            else if (sOldValue != sCurrentValue)
                                sRet = true;
                            break;
                        default:
                            if (sOldValue != sCurrentValue)
                                sRet = true;
                            break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("AuditLog: IsNewValue : Error : " + ex.Message);
        }
        return sRet;
    }
}